<script setup lang="ts">
import modalBody from './modal-body/index.vue';
import Arithmetic from '@/views/Demand/components/arithmetic.vue';
import { searchConfig } from './config/search-config.ts';
import { tableConfig } from './config/table-config.ts';
import { generateNameToLevel } from '@/config/constant';
import { doGetOrderList } from '@/api/demand/arithmetic/index';
import useCommon from '@/views/Demand/Arithmetic/hooks';
import { Modal } from '@/instance';
import type { ScheduleListListInfo } from '@/api/demand/arithmetic/model/type.ts';

const emit = defineEmits(['getData']);

const visible = ref(false);

const tableRef = ref<TableRef>();
const { updateSelect } = useCommon(tableRef);
const check = ref(false);

/**
 * @: 打开弹框
 */
const open = () => {
    visible.value = true;
};

/**
 * @: 点击弹框确定
 */
const arithmeticRef = ref<InstanceType<typeof Arithmetic>>();
const handleOk = () => {
    Modal.info({
        title: '选择订单！',
        content: h(modalBody, { length: selectIds.value.length, check: check.value, onCheck }),
        okText: '确定插单排产',
        okCancel: true,
        width: '480px',
        onOk() {
            arithmeticRef.value?.open('ORDER_INSERT_OPERATION', { firstOrder: check.value });
            visible.value = false;
        }
    });
};

/**
 * @: 是否是第一顺位
 */
const onCheck = (val: boolean) => {
    check.value = val;
};

/**
 * @: 选择订单
 */
const searchRef = ref<SearchRef>();
const selectIds = ref<string[]>([]);
const handleSelection = (e: ScheduleListListInfo[]) => {
    selectIds.value = e.map(item => item.orderNumber);
};

defineExpose({
    open
});
</script>

<template>
    <q-modal
        v-model:visible="visible"
        centered
        title="选择订单"
        width="1140px"
        :ok-button-props="{
            disabled: !selectIds.length
        }"
        @ok="handleOk"
    >
        <base-search ref="searchRef" :search-config="searchConfig" :table-ref="tableRef" />
        <base-table
            :id="generateNameToLevel('1')"
            ref="tableRef"
            modal-mode
            :added-params="{ schedulingStatuses: ['NOTARRANGED', 'ARRANGED'] }"
            :table-config="tableConfig"
            :getDataFn="doGetOrderList"
            :show-setting="false"
            @selection-change="handleSelection"
        />
    </q-modal>

    <!-- 计划运算 -->
    <arithmetic
        ref="arithmeticRef"
        :ids="selectIds"
        @get-data="emit('getData')"
        @update-select="updateSelect"
    />
</template>

<style scoped lang="scss"></style>
